<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Request;
use think\Config;

class Notice extends AdminBase {
  protected $model;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->model = new \app\admin\model\Notice();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {
    if (!request()->isPost()) {
      $rows = $this->model
        ->alias('k')
        ->join('__BASE_USER__ u', 'u.id=k.creator_uid', 'left')
        ->field('k.*,u.realname')
        ->order('k.sort DESC,k.create_time DESC')
        ->paginate();

      return view('', ['rows' => $rows]);
    }
    $sort = input('sort/a', NULL);
    $data = [];
    foreach ($sort as $id => $v) {
      $data[] = ['id'   => $id,
                 'sort' => $v];
    }
    try {
      $this->model->saveAll($data);
    } catch (Exception $e) {
      $this->error($e->getMessage());
    }

    $this->success(lang('success'));

  }

  public function add() {
    return self::edit();
  }

  public function edit() {
    $id = input('id/d', 0, 'abs');
    if (!request()->isPost()) {
      $row = ($id > 0) ? $this->model->find($id) : [];

      return view('edit', ['row' => $row]);
    }
    $form = input('form/a', NULL);
    $result = $this->validate($form, 'Notice');
    if (TRUE !== $result) {
      $this->error($result);
    }
    cmf_log('新增/编辑公告', $id, $form['title']);
    $this->model->editJump($form, $id, url('index'));

  }

  public function delete() {
    $id = input('id/d', 0, 'abs');
    $r = $this->model->destroy($id);
    if (!$r) $this->error(lang('error') . $this->model->getError());

    cmf_log('删除公告', $id);
    $this->success(lang('success'));
  }


}